package com.seu.vcampus.dao;

import com.seu.vcampus.vo.CartItem;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;

/**
 * 购物车内容数据访问类 
 * 负责购物车内容的CRUD操作
 * 
 * @author 虚拟校园开发团队
 * @since 1.0.0
 */
public class CartItemDao {
	private final Connection connection;
	
	private static final String selectItem = "SELECT * FROM CartItem WHERE user = ?, product = ?";
	private static final String selectUserAll = "SELECT * FROM CartItem WHERE user = ?";
	private static final String insertItem = "INSERT INTO CartItem (user, product, quantity) VALUES (?, ?, ?)";
	private static final String deleteItem = "DELETE FROM CartItem WHERE user = ?, product = ?";
	private static final String deleteUserAll = "DELETE FROM CartItem WHERE user = ?";
	private static final String updateItem = "UPDATE CartItem SET user = ?, product = ?, quantity = ?";
	private static final String countUserItem = "SELECT COUNT(*) FROM CartItem WHERE user = ?";
	
	public CartItemDao(Connection connection)
	{
		this.connection = connection;
		initializeTable();
	}
	
	/**
	 * 初始化购物车内容表 
	 */
	private void initializeTable()
	{
		try(Statement stmt = connection.createStatement())
		{
			String createCartItemTable = "CREATE TABLE IF NOT EXISTS CartItem("
					+ "user VARCHAR(50) PRIMARY KEY, "
					+ "product VARCHAR(50) NOT NULL UNIQUE, "
					+ "quantity INTEGER NOT NULL"
					+ ")";
			stmt.execute(createCartItemTable);
		}
		catch(SQLException e)
		{
			throw new RuntimeException("Failed to initialize CartItem table", e);
		}
	}
	
	/**
	 * 保存购物车记录
	 * @param CartItem 购物车内容对象
	 * @return 是否保存成功
	 */
	public boolean save(CartItem c)
	{
		CartItem existingCartItem = findById(c.getUser(), c.getProduct());
		
		if(existingCartItem == null)
		{
			try(PreparedStatement stmt = connection.prepareStatement(insertItem))
			{
				stmt.setString(1, c.getUser());
				stmt.setString(2, c.getProduct());
				stmt.setInt(3, c.getQuantity());
				
				return stmt.executeUpdate() > 0;
			}
			catch(SQLException e)
			{
				throw new RuntimeException("Failed to save CartItem", e);
			}
		}
		else
		{
			try(PreparedStatement stmt = connection.prepareStatement(updateItem))
			{
				stmt.setString(1, c.getUser());
				stmt.setString(2, c.getUser());
				stmt.setInt(3, c.getQuantity());
				return stmt.executeUpdate() > 0;
			}
			catch(SQLException e)
			{
				throw new RuntimeException("Failed to update CartItem", e);
			}
		}
	}
	
	/**
	 * 删除购物车记录
	 * @param uid 用户ID
	 * @param pid 商品ID
	 * @return 是否删除成功
	 */
	public boolean delete(String uid, String pid)
	{
		try(PreparedStatement stmt = connection.prepareStatement(deleteItem))
		{
			stmt.setString(1, uid);
			stmt.setString(2, pid);
			return stmt.executeUpdate() > 0;
		}
		catch(SQLException e)
		{
			throw new RuntimeException("Failed to delete CartItem", e);
		}
	}
	
	/**
	 * 删除用户所有购物车记录
	 * @param uid 用户ID
	 * @return 是否删除成功 
	 */
	public boolean deleteUserAll(String uid)
	{
		try(PreparedStatement stmt = connection.prepareStatement(deleteUserAll))
		{
			stmt.setString(1, uid);
			return stmt.executeUpdate() > 0;
		}
		catch(SQLException e)
		{
			throw new RuntimeException("Failed to delete user all CartItem", e);
		}
	}
	
	/**
	 * 更新购物车记录
	 * @param c 购物车内容对象
	 * @return 是否更新成功 
	 */
	public boolean update(CartItem c)
	{
		try(PreparedStatement stmt = connection.prepareStatement(updateItem))
		{
			stmt.setString(1, c.getUser());
			stmt.setString(2, c.getProduct());
			stmt.setInt(3, c.getQuantity());
			return stmt.executeUpdate() > 0;
		}
		catch(SQLException e)
		{
			throw new RuntimeException("Failed to update CartItem", e);
		}
	}
	
	/**
	 * 获取用户购物车内容数量
	 * @param uid 用户ID
	 * @return 购物车内容数量
	 */
	public int getUserCartCount(String uid)
	{
		try(PreparedStatement stmt = connection.prepareStatement(countUserItem))
		{
			ResultSet rs = stmt.executeQuery();
			return rs.next() ? rs.getInt(1) : 0;
		}
		catch(SQLException e)
		{
			throw new RuntimeException("Failed to get user CartItem count", e);
		}
	}
	
	/**
	 * 根据用户ID和商品ID查找购物车记录
	 * @param uid 用户ID
	 * @param pid 商品ID
	 * @return 购物车内容对象，不存在返回null
	 */
	public CartItem findById(String uid, String pid)
	{
		try(PreparedStatement stmt = connection.prepareStatement(selectItem))
		{
			ResultSet rs = stmt.executeQuery();
			if(rs.next())
			{
				return mapResultSetToCartItem(rs);
			}
			return null;
		}
		catch(SQLException e)
		{
			throw new RuntimeException("Failed to find CartItem", e);
		}
	}
	
	/**
	 * 根据用户ID查找用户所有购物车记录
	 * @param uid 用户ID
	 * @return 购物车内容对象列表
	 */
	public List<CartItem> findUserAll(String uid)
	{
		try(PreparedStatement stmt = connection.prepareStatement(selectUserAll))
		{
			ResultSet rs = stmt.executeQuery();
			List<CartItem> ret = new ArrayList<>();
			
			while(rs.next())
			{
				ret.add(mapResultSetToCartItem(rs));
			}
			return ret;
		}
		catch(SQLException e)
		{
			throw new RuntimeException("Failed to find user all CartItem", e);
		}
	}
	
	/**
	 * 将ResultSet对象映射为CartItem
	 * @param rs 结果集对象
	 * @return 购物车内容对象
	 */
	public CartItem mapResultSetToCartItem(ResultSet rs) throws SQLException
	{
		return new CartItem(rs.getString("user"), rs.getString("product"), rs.getInt("quantity"));
	}
	
	
	
	
}

